package drds.server.route;

import java.sql.SQLNonTransientException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import drds.server.cache.CacheService;
import drds.server.cache.ICache;
import drds.server.cache.LayeredCache;
import drds.server.config.model.DRDS;
import drds.server.config.model.Schema;
import drds.server.server.SessionContext;
import drds.server.server.parser.ServerParse;

public class RouteService {
	private static final Logger LOGGER = LoggerFactory.getLogger(RouteService.class);
	public static final String _HINT_TYPE = "_HintType";
	private final ICache routeCache;
	private final LayeredCache tableId2DataNodeCache;

	public RouteService(CacheService cachService) {
		routeCache = cachService.getCachePool("sqlroutecache");
		tableId2DataNodeCache = (LayeredCache) cachService.getCachePool("tableid2datanodecache");
	}

	public LayeredCache getTableId2DataNodeCache() {
		return tableId2DataNodeCache;
	}

	public Route route(DRDS drds, Schema schema, int sqlType, String sql, String charset, SessionContext sc) throws SQLNonTransientException {
		Route route = null;
		String cacheKey = null;

		/**
		 * SELECT 类型的SQL, 检测
		 */
		if (sqlType == ServerParse.SELECT) {
			cacheKey = schema.getName() + sql;
			route = (Route) routeCache.get(cacheKey);
			if (route != null) {
				return route;
			}
		}

		route = RouteStrategyFactory.getRouteStrategy().route(sc, schema, sql, sqlType, tableId2DataNodeCache);

		if (route != null && sqlType == ServerParse.SELECT && route.isCache()) {
			routeCache.putIfAbsent(cacheKey, route);
		}
		return route;
	}
}